package frame;

import bean.Parametrizacao;
import bean.Tarefa;
import com.toedter.calendar.JCalendar;
import com.toedter.calendar.JDateChooser;
import controle.CalcHora;
import controle.GeraRelatorio;
import dao.TarefaDAO;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

public class RendimentosFrame extends javax.swing.JFrame {

    private List<Tarefa> lista;
    GeraRelatorio rel = new GeraRelatorio();
    private int tamanho_lista, total_minutos, min_extra, total_min_extra, total_min_neg, difDia;
    String min_hora, hora_extra;
    double valor_min, valor_hora  ;
    CalcHora calc = new CalcHora( );
    DecimalFormat df = new DecimalFormat("R$ #,##0.00");//formato  
    DecimalFormat df2 = new DecimalFormat("#,##0.00");//formato  
    SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat data2 = new SimpleDateFormat("ddMM");
    boolean fin_sem = false;

    public RendimentosFrame() {
        initComponents();
        setParameter();
        JTableHeader titulos = jTable1.getTableHeader();
        jFormattedTextField_valorhora.setHorizontalAlignment(jFormattedTextField_valorhora.CENTER);
        titulos.setFont( new Font("Dialog", Font.BOLD, 10));
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton_enviar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jTextField_horaextra = new javax.swing.JTextField();
        jTextField_totalreceber = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jDateChooser_datafinal = new com.toedter.calendar.JDateChooser();
        jDateChooser_datainicial = new com.toedter.calendar.JDateChooser();
        jFormattedTextField_valorhora = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField_totalhoras = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jCheckBox = new javax.swing.JCheckBox();

        setTitle("Rendimentos");
        setResizable(false);
        getContentPane().setLayout(null);

        jButton_enviar.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jButton_enviar.setText("OK");
        jButton_enviar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_enviarActionPerformed(evt);
            }
        });
        getContentPane().add(jButton_enviar);
        jButton_enviar.setBounds(10, 90, 50, 20);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "DATA", "H.TRAB", "H.EXTRA", "À RECEBER"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setEnabled(false);
        jScrollPane1.setViewportView(jTable1);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(10, 120, 320, 180);

        jTextField_horaextra.setEditable(false);
        jTextField_horaextra.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField_horaextra.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jTextField_horaextra);
        jTextField_horaextra.setBounds(170, 60, 80, 18);

        jTextField_totalreceber.setEditable(false);
        jTextField_totalreceber.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField_totalreceber.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jTextField_totalreceber);
        jTextField_totalreceber.setBounds(250, 60, 80, 18);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabel1.setText("  H.EXTRA");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(180, 50, 70, 13);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabel4.setText("     R$ HORA");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(10, 50, 80, 13);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("  CONSULTAR RENDIMENTO MENSAL");
        jLabel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jLabel3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel3MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel3);
        jLabel3.setBounds(30, 10, 280, 30);

        jDateChooser_datafinal.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jDateChooser_datafinal);
        jDateChooser_datafinal.setBounds(180, 90, 100, 24);

        jDateChooser_datainicial.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jDateChooser_datainicial);
        jDateChooser_datainicial.setBounds(70, 90, 100, 24);

        jFormattedTextField_valorhora.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jFormattedTextField_valorhora.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#,##0.00"))));
        jFormattedTextField_valorhora.setText("0");
        jFormattedTextField_valorhora.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFormattedTextField_valorhoraActionPerformed(evt);
            }
        });
        jFormattedTextField_valorhora.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jFormattedTextField_valorhoraFocusGained(evt);
            }
        });
        getContentPane().add(jFormattedTextField_valorhora);
        jFormattedTextField_valorhora.setBounds(10, 60, 80, 18);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabel2.setText("    À RECEBER");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(250, 50, 80, 13);

        jTextField_totalhoras.setEditable(false);
        jTextField_totalhoras.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jTextField_totalhoras.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        getContentPane().add(jTextField_totalhoras);
        jTextField_totalhoras.setBounds(90, 60, 80, 18);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jLabel5.setText("      H.TRAB");
        getContentPane().add(jLabel5);
        jLabel5.setBounds(90, 50, 80, 13);

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/relatorio.gif"))); // NOI18N
        getContentPane().add(jLabel6);
        jLabel6.setBounds(300, 80, 30, 40);
        getContentPane().add(jCheckBox);
        jCheckBox.setBounds(280, 90, 20, 20);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-344)/2, (screenSize.height-336)/2, 344, 336);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_enviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_enviarActionPerformed
       
        if ( jDateChooser_datainicial.getDate() == null ){
           JOptionPane.showMessageDialog(null, "Data Inicial Invalida !");
        }
        else if ( jDateChooser_datafinal.getDate() == null ){
           JOptionPane.showMessageDialog(null, "Data Final Invalida !");
        }
        else if ( jDateChooser_datainicial.getDate().after(jDateChooser_datafinal.getDate( ) ) ){
           JOptionPane.showMessageDialog(null, "Data inicial maor que data final !");
        }
        else if ( jFormattedTextField_valorhora.getText().equals("") ){
           JOptionPane.showMessageDialog(null, "Digite o valor da hora !");    
        }
        else
         preencher_jtable();
        updateParametr();
               
    }//GEN-LAST:event_jButton_enviarActionPerformed

    private void jFormattedTextField_valorhoraFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField_valorhoraFocusGained
        jFormattedTextField_valorhora.requestFocus();
    }//GEN-LAST:event_jFormattedTextField_valorhoraFocusGained

    private void jLabel3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel3MouseClicked
 
             java.util.Date di = jDateChooser_datainicial.getDate();
             int mes = di.getMonth()+1;
             di.setMonth(mes);
             jDateChooser_datainicial.setDate(di);
             
             java.util.Date df = jDateChooser_datafinal.getDate();
             int mesf = df.getMonth()+1;
             df.setMonth(mesf);
             jDateChooser_datafinal.setDate(df);               
        
    }//GEN-LAST:event_jLabel3MouseClicked

    private void jFormattedTextField_valorhoraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFormattedTextField_valorhoraActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jFormattedTextField_valorhoraActionPerformed
 
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new RendimentosFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_enviar;
    private javax.swing.JCheckBox jCheckBox;
    private com.toedter.calendar.JDateChooser jDateChooser_datafinal;
    private com.toedter.calendar.JDateChooser jDateChooser_datainicial;
    private javax.swing.JFormattedTextField jFormattedTextField_valorhora;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_horaextra;
    private javax.swing.JTextField jTextField_totalhoras;
    private javax.swing.JTextField jTextField_totalreceber;
    // End of variables declaration//GEN-END:variables

    
    private void preencher_jtable( ) {

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();  
        centralizado.setHorizontalAlignment(SwingConstants.CENTER);  
        
        JTableHeader titulos = jTable1.getTableHeader();
        titulos.setFont( new Font("Dialog", Font.BOLD, 10));
        jTable1.getColumnModel().getColumn(0).setCellRenderer(centralizado);  
        jTable1.getColumnModel().getColumn(1).setCellRenderer(centralizado);  
        jTable1.getColumnModel().getColumn(2).setCellRenderer(centralizado);  
        jTable1.getColumnModel().getColumn(3).setCellRenderer(centralizado);   
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(20);
        jTable1.getColumnModel().getColumn(3).setPreferredWidth(20);        
        total_min_extra = 0;
        total_min_neg = 0;
        total_minutos =0;
        try {
            java.util.Date dataUtilini = new java.util.Date();  
            java.sql.Date dataini = new java.sql.Date(jDateChooser_datainicial.getDate().getTime());  
            
            java.util.Date dataUtilfim = new java.util.Date();  
            java.sql.Date datafim = new java.sql.Date(jDateChooser_datafinal.getDate().getTime() );  
    
            Tarefa t = new Tarefa();
            TarefaDAO dao = new TarefaDAO();
             
            lista = dao.somaPorPeriodo( dataini, datafim );
            tamanho_lista = lista.size();
            String dados = "";
            
            int dia, mes, ano;
                
            if (tamanho_lista<1) {
                JOptionPane.showMessageDialog(null, "Nenhum registro encontrado !");
            }
            
            String hora_valor = jFormattedTextField_valorhora.getText( ).replace(",", ".") ;
            valor_hora =  Double.parseDouble( hora_valor );
             
            valor_min =   valor_hora  / 60;
            total_minutos = 0 ;
            String texto = "";
           
            for (int i = 0; i < tamanho_lista; i++) {
                t = lista.get(i);
                
              dia = t.getData_tarefa().getDate();
              mes = t.getData_tarefa().getMonth()+1;
              ano = t.getData_tarefa().getYear()+1900;
           
              fin_sem = isFinalDeSemana(ano, mes, dia); 
              
              if( !data.format( t.getData_tarefa() ).equals( data.format( new java.util.Date()) ) || (  data.format( t.getData_tarefa() ).equals( data.format( new java.util.Date()) ) &&  t.getMinutos()>=480) )
              { 
              
              total_minutos = total_minutos + t.getMinutos();
                            
                if ( t.getMinutos() < 480 && !fin_sem ) {
                      difDia = 480 - t.getMinutos();
                    total_min_neg += difDia;
                    min_extra = t.getMinutos() -480;
                }
                  
                if ( t.getMinutos() >= 480 && !fin_sem ) {
                     min_extra = t.getMinutos() - 480;
                }
                else if ( fin_sem ){
                   min_extra =  t.getMinutos(); 
                }                                
                
                  if (jCheckBox.isSelected()) {
                      
              HashMap<String,String> mapa = rel.montaLinha(t.getData_tarefa()); 

               texto +=
               data.format(t.getData_tarefa())+ " " +
               mapa.get("horaEntrada")+ " " +
               mapa.get("horaSaida")+ " " +
               mapa.get("total")+ " " +
               mapa.get("almoco")+ "  " +
               calc.minParaHora(t.getMinutos())+ "  " +
               calc.minParaHoraExtra( min_extra)+ " " +
               df2.format( t.getMinutos() * valor_min ) +"\n"+
               "------------------------------------------------------------\n"
              ; }

               
                modelo.addRow(new Object[]{
                           data.format(t.getData_tarefa()),
                       calc.minParaHora(t.getMinutos()),
                       calc.minParaHoraExtra(min_extra),
                      df.format( t.getMinutos() * valor_min ),
                     });
                              
                if( min_extra > 0 ) 
                total_min_extra += min_extra;
              }  
            
            }
            
            
            if (jCheckBox.isSelected()) {
            String nome = "RelHoras"+data2.format(jDateChooser_datainicial.getDate())+"a"+data2.format(jDateChooser_datafinal.getDate())+"_";
            String header = "\n\nRelatório de Horas de " +data.format(dataini)+" até "+data.format(datafim)+"\n\n\n"+
			"Data     Entrada Saida Total Almoço H.Trab H.Extra  R$ Dia"+"\n\n";
            String total = 
        	   "                            Total= "
        	   +calc.minParaHora( total_minutos )+"  "+
                    calc.minParaHoraExtra( total_min_extra-total_min_neg)+" "+
                    df2.format( total_minutos*valor_min )+"\n"  ;            
           
           rel.gerarArquivo( texto, header, total, nome );
           
            }
            
            alinhaSetaCampos(total_minutos, valor_min);
            
            if (!lista.isEmpty()) {
                t = lista.get(0);
                jTable1.setRowSelectionInterval(0, 0);
            }
                        
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "erro ao listar Jtable" + erro); 
        }
    }
    
    public void alinhaSetaCampos( int min, double valor_min ){              
        
        jFormattedTextField_valorhora.setHorizontalAlignment(jFormattedTextField_valorhora.CENTER);
        jTextField_totalhoras.setHorizontalAlignment(jTextField_horaextra.CENTER);
        jTextField_totalreceber.setHorizontalAlignment(jTextField_totalreceber.CENTER);
        jTextField_horaextra.setHorizontalAlignment(jTextField_totalreceber.CENTER);
        jFormattedTextField_valorhora.setText(""+ df2.format( valor_hora ) );            
        jTextField_totalhoras.setText(calc.minParaHora( min ) );
        jTextField_totalreceber.setText(""+ df2.format( min*valor_min ) );            
        jTextField_horaextra.setText( ""+ calc.minParaHora( total_min_extra-total_min_neg) );
    }
        
    private boolean isFinalDeSemana(int ano, int mes, int dia) throws Exception {
        if ((mes < 1) || (mes > 12)) {
            throw new Exception("Mês inválido");
        }

        boolean finalDeSemana;
        mes = mes - 1;
        Calendar data = new GregorianCalendar();

        data.set(ano, mes, 1);
        int diaMaximo = data.getActualMaximum(Calendar.DAY_OF_MONTH);

        if (diaMaximo < dia) {
            throw new Exception("Dia inválido");
        }

        data.set(ano, mes, dia);
        int diaDaSemana = data.get(Calendar.DAY_OF_WEEK);

        if ((diaDaSemana == Calendar.SATURDAY) || (diaDaSemana == Calendar.SUNDAY)) {
            finalDeSemana = true;
        } else {
            finalDeSemana = false;
        }

        return finalDeSemana;
    }
    
    public void updateParametr( ) {

    	TarefaDAO daoprm1 =  new TarefaDAO();
    	TarefaDAO daoprm2 =  new TarefaDAO();
    	TarefaDAO daoprm3 =  new TarefaDAO();
    	TarefaDAO daoprm4 =  new TarefaDAO();
    	
    	try {
			Map<String, String> mapa = daoprm1.getPrm();
			
			String dataIniPrm = mapa.get("inicio");
			String dataFimPrm = mapa.get("fim");
			String valorPrm = mapa.get("valor");
			
			String dataFimFrm =	data.format(jDateChooser_datafinal.getDate().getTime());
			String dataIniFrm =	data.format(jDateChooser_datainicial.getDate().getTime());
			String valorFrm = jFormattedTextField_valorhora.getText();
			
			if ( !valorFrm.equals( valorPrm ) ) {
				Parametrizacao param = new Parametrizacao();
				param.setParametro( "valor" );
				param.setValor( valorFrm );
				daoprm2.updatePrm( param );
			}
			
			if ( !dataIniFrm.equals( dataIniPrm ) ) {
				Parametrizacao param1 = new Parametrizacao();
				param1.setParametro( "inicio" );
				param1.setValor( dataIniFrm );
				daoprm3.updatePrm( param1 );
			}
			
			if ( !dataFimFrm.equals( dataFimPrm ) ) {
				Parametrizacao param2 = new Parametrizacao();
				param2.setParametro( "fim" );
				param2.setValor( dataFimFrm );
				daoprm4.updatePrm( param2 );
			}
		
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
    
    public void setParameter( ) {
    	TarefaDAO daoprm1 =  new TarefaDAO();
    	try {
			Map<String, String> mapa = daoprm1.getPrm();
			String dataIniPrm = mapa.get("inicio");
			String dataFimPrm = mapa.get("fim");
			String valorPrm = mapa.get("valor");
			Date dataini =  data.parse(dataIniPrm);
			Date datafim = data.parse(dataFimPrm);
			jFormattedTextField_valorhora.setText(valorPrm);
			jDateChooser_datafinal.setDate( datafim );
			jDateChooser_datainicial.setDate( dataini);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
    
    
}
